package com.hbhmzy.utils;

import android.content.Context;
import android.util.Log;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.CountDownLatch;


/**
 * 客户端发送请求
 *
 * @author zhb
 */
public class Client {
    public  Context context;
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    CountDownLatch latch = new CountDownLatch(1);
    public static Channel channel = null;
    // 要请求的服务器的ip地址
    private String ip;
    // 服务器的端口
    private int port;

    public Client(String ip, int port,Context context) {
        this.ip = ip;
        this.port = port;
        this.context=context;
    }
    public Client(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    // 请求端主题
    public void action() throws InterruptedException, UnsupportedEncodingException {

        Bootstrap bs = new Bootstrap();
        bs.group(bossGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 处理来自服务端的响应信息
                        socketChannel.pipeline().addLast(new ClientHandler(context));
                    }
                });

        // 客户端开启
        ChannelFuture cf = bs.connect(ip, port).sync();
        channel = cf.channel();
        latch.countDown();


        // 等待直到连接中断
       // channel.closeFuture().sync();
    }

//    public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {
//        new Client1("127.0.0.1", 36346).action();
//
//
//        System.out.println("11111111111111111111111");
//        new Thread(() -> {
//            while (true) {
//                try {
//                    Thread.sleep(1111);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                send();
//            }
//        }).start();
//    }


    public static void send(String s){
        try {
            Log.e("SendbyTCP", s );
            channel.writeAndFlush(Unpooled.copiedBuffer(s.getBytes("utf8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
